package main

import (
	"net/http"
	"html/template"
	"fmt"
	"time"
)

func viewData(w http.ResponseWriter,r *http.Request)  {
	t,_:=template.ParseFiles("testserverevent.html")
	_=t.Execute(w,nil)
}

func getDate(w http.ResponseWriter,r *http.Request)  {
	fmt.Println("enter getDate.")
	for{
			w.Header().Set("Content-Type","text/event-stream;charset=utf-8")
			w.Header().Set("Catch-Control","no-cache")
			dtstr :="data:" + fmt.Sprint(time.Now()) +"\n\n"
			dtstr = dtstr + "retry:"+"1000"+"\n\n"
			w.Write([]byte(dtstr))

			if f,ok :=w.(http.Flusher);ok{
				f.Flush()
			}else{
				fmt.Println("no flush")
			}
			time.Sleep(10000*time.Millisecond)
	}
}

func main()  {
	fmt.Println("enter main.")

	http.HandleFunc("/",viewData)
	http.HandleFunc("/getdate",getDate)
	http.ListenAndServe(":3000",nil)

}

//func main()  {
//	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
//		writer.Write([]byte(`Hello world`))
//	})
//
//	http.ListenAndServe(":3000",nil)
//}